using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;

namespace GetWebData
{
    public class RequestWebData
    {
        public string PostFile(string weburl, string path, string data, string fileName)
        {
            var client = HttpClientFactory.Create();
            var content = new MultipartFormDataContent();
            //添加字符串参数，参数名为data
            content.Add(new StringContent(data), "data");
            //string path = Path.Combine(System.Environment.CurrentDirectory, "1.png");
            //添加文件参数，参数名为files，文件名为123.png
            content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", fileName);
            // var requestUri = "https://tapi.juzishu.com.cn/onlineeducation/api/upload/uploadMusic";
            var requestUri = weburl;
            var result = client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;
            return result;
        }
        public string Post(string url, Object obj)
        {
            try
            {
                var jsondata = JsonConvert.SerializeObject(obj);
                var client = HttpClientFactory.Create();
                var responseMessage = client.PostAsync(url, new StringContent(jsondata, Encoding.UTF8, "application/json")).Result;
                return responseMessage.Content.ReadAsStringAsync().Result;
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
        private string Post(string url,params string[] par)
        {
            try
            {
                string jsondata = "";
                for (int i = 0; i < par.Length; i++)
                {
                    if (i>0)
                    {
                        jsondata += "&";
                    }
                    jsondata += par[i];
                }
                var client = HttpClientFactory.Create();
                var responseMessage = client.PostAsync(url, new StringContent(jsondata, Encoding.UTF8, "application/json")).Result;
                return responseMessage.Content.ReadAsStringAsync().Result;
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
        public string Get(string url)
        {
            try
            {
                var client = HttpClientFactory.Create();
                var responseMessage = client.GetAsync(url, HttpCompletionOption.ResponseContentRead).Result;
                return responseMessage.Content.ReadAsStringAsync().Result;
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
    }

}
